use std::io::stdin;
// 宏的作用是,可以用{:?}打印结构体
#[derive(Debug)]
struct Visitor {
    name: String,
    // 增加年龄字段,用来判断是否为成年人
    age: i8,
    action:VisitorAction,
}

impl Visitor {

    fn new(name: &str, age: i8, action:VisitorAction) -> Self {
        // 缺失的;分号表示隐式返回
        Self {
            name: name.to_string(),
            age,
            action,
        }
    }
    
    fn greet_visitor(&self) {
        match &self.action {
            VisitorAction::Accept => println!("welcome to the treehouse,{}", self.name),
            VisitorAction::AcceptWithNote { note } => {
                println!("welcome to the treehouse,{}", self.name);
                println!("{}",note);
                if self.age < 21 {
                    println!("do not serve alcohol to {}", self.name)
                }

            },
            VisitorAction::Probation => println!("{} is show a probationary member", self.name),
            VisitorAction::Refuse => println!("do not allow, {}", self.name)
        }
    }
}

// 增加枚举实现人员分类, 枚举和结构体一样,不需要分号结束
#[derive(Debug)]
enum VisitorAction {
    // 枚举项---无关联数据, let z = VisitorAction::Accept赋值
    Accept,
    // 枚举项---有关联数据, let z = VisitorAction::AcceptWithNote{note:"hello".to_string()}赋值
    AcceptWithNote{note:String},
    Refuse,
    Probation,
}



fn main() {
    let mut visitor_list = Vec::new();
    // 数组改为向量,因为要动态扩容
    visitor_list.push(Visitor::new("bert", 45, VisitorAction::Accept));
    visitor_list.push(Visitor::new("steve", 15, VisitorAction::AcceptWithNote { note: "milk location in fridge".to_string() }));
    visitor_list.push(Visitor::new("bob", 30, VisitorAction::Refuse));

    loop {
        println!("Hello, what's you name?");
        let your_name = what_is_your_name();
        // 迭代器判断是否为可访问人员, 迭代器链式调用+闭包的使用
        let known_visitor = visitor_list.iter().find(|visitor| *visitor.name == your_name );
    
        match known_visitor {
            Some(visitor) => visitor.greet_visitor(),
            None => {
                // String字符串判空方法
                if your_name.is_empty(){
                    break;
                }else{
                    println!("{} is not in visitor_list",your_name);
                    visitor_list.push(Visitor::new(your_name.as_str(), 20, VisitorAction::Probation));
                }
            }
        }
    }
   
    // 打印访问名单
    println!("the last visitor list:");
    println!("{:#?}", visitor_list);

   
}


fn what_is_your_name () -> String {
    let mut your_name = String::new();
    stdin().read_line(&mut your_name).expect("failed to readline");
    your_name.trim().to_lowercase()
}

